import time
import os
import random

# 批量重命名指定目录下的子目录为随机名称
# 使用: 将输出结果作为shell脚本

def decimal_to_base62(num):
    """
    将一个十进制整数转换为62进制的字符串
    :param num: 十进制整数
    :return: 62进制的字符串表示
    """
    if num == 0:
        return "0"

    charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    result = []

    while num > 0:
        remainder = num % 62
        result.append(charset[remainder])
        num = num // 62

    # 由于是逐位取余,结果需要反转
    return "".join(reversed(result))


# 使用time.time()方法生成当前时间的时间戳,并将其左移32位
# 然后,使用一个计数器来确保每次生成的整数都是唯一的
def generate_unique_integer(counter):
    unique_integer = int(time.time()) << 32 | counter
    return unique_integer


def get_subfolder_names(directory_path):
    """
    获取指定目录下所有子文件夹的名称,并返回一个包含这些名称的列表
    :param directory_path: 要遍历的目录路径
    :return: 包含所有子文件夹名称的列表
    """
    try:
        # 使用os.listdir列出目录下的所有内容
        entries = os.listdir(directory_path)
        # 过滤出其中的目录（文件夹）
        subfolders = [
            entry
            for entry in entries
            if os.path.isdir(os.path.join(directory_path, entry))
        ]

        return subfolders
    except FileNotFoundError:
        print(f"目录未找到: {directory_path}")
        return []
    except PermissionError:
        print(f"权限不足,无法访问目录: {directory_path}")
        return []
    except Exception as e:
        print(f"发生错误: {e}")
        return []


def obtains_shuffled_str(unique_string):
    # 反转字符串
    reverse_unique = "".join(reversed(unique_string))
    # 字符串不可变,先变成列表
    lst = list(reverse_unique)
    # 就地打乱
    random.shuffle(lst)
    shuffled = "".join(lst)
    return shuffled


def unions(directory_path):
    s = " "
    unix_separator = "/"
    parentDirPath = f"{unix_separator}{directory_path}{unix_separator}"

    subfolder_names = get_subfolder_names(directory_path)
    # 使用 random.shuffle 打乱列表
    random.shuffle(subfolder_names)

    for index, subfolder in enumerate(subfolder_names):
        counter = index + 1

        unique_number = generate_unique_integer(counter)
        unique_string = decimal_to_base62(unique_number)

        shuffle_str = obtains_shuffled_str(unique_string)

        cmd_sentence = (
            f'mv{s}"{parentDirPath}{subfolder}"{s}{parentDirPath}{shuffle_str};'
        )

        cmd_sentence = cmd_sentence.replace(":", "")
        cmd_sentence = cmd_sentence.replace("\\", unix_separator)

        print(cmd_sentence)
        time.sleep(0.1)


# 示例用法
if __name__ == "__main__":
    directory_path = r"D:\sss"
    unions(directory_path)
